''''用户账户相关功能'''
"""测试账户密码
username:XXXX
password:XXXXXXX
moible_phone:XXXXXXX
"""
import uuid
import datetime
from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from web import models
#注册
#模板查找顺序查找HTML

from web.forms.account import RegisterModelForm,SendSmsForm,LoginSmsForm,LoginForm
def register(request):
    if request.method == "GET":
        form = RegisterModelForm()
        return render(request,"web/register.html",{'form':form})
    #对于POST提交的表单进行校验
    #print(request.POST)
    # return HttpResponse('成功！')
    elif request.method == "POST":
        form = RegisterModelForm(request.POST)

        if form.is_valid():
            print(form.cleaned_data)
            instace = form.save()
            policy_object = models.PricePolicy.objects.filter(category=1,title="个人免费版").first()
            #创建一条交易记录
            models.Transaction.objects.create(
                status = 2,
                order=str(uuid.uuid4()),
                user = instace,
                price_policy=policy_object,
                count=0,
                price = 0,
                start_datetime=datetime.datetime.now()

            )
            return JsonResponse({'status':True,'data':'/login/'})
        return JsonResponse({'status':False,'error':form.errors})

def send_sms(request):

    """发送短信"""
    form = SendSmsForm(request,data=request.GET)
    #校验手机号:格式是否正确，是否为空
    if form.is_valid():
        #验证通过发短信
        return JsonResponse({'status':True})
    return JsonResponse({'status':False,'error':form.errors})

#短信登陆
def login_sms(request):
    '''短信登陆'''
    if request.method=="GET":
        form = LoginSmsForm()
        return render(request,'web/login_sms.html',{'form':form})

    elif request.method == "POST":
        form = LoginSmsForm(request.POST)
        if form.is_valid():
            #验证完成登录,进入主页
            user_object = form.cleaned_data['mobile_phone']
            print(user_object.username)
            request.session['user_id'] = user_object.id
            #将用户信息放入session
            return JsonResponse({'status':True,'data':'/index/'})
        return JsonResponse({'status':False,'errors':form.errors})

#账号密码登陆
def login(request):
    """手机号登陆"""
    if request.method =="GET":
        form = LoginForm(request)
        return render(request,'web/login.html',{"form":form})
    form = LoginForm(request,request.POST)
    if form.is_valid():

        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        from django.db.models import Q
        #构造复杂匹配查询条件Q
        user_object = models.UserInfo.objects.filter(Q(email=username)|Q(mobile_phone=username)).filter(password=password).first()
        #print(user_object.id)
        if user_object:
            #用户名密码正确

            #用户信息保存两周
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60*60*24*14)
            return redirect('index')
        form.add_error('username','用户名密码错误')
    return render(request, 'web/login.html', {"form": form})




#验证码生成
def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    from utils.draw_test import check_code
    #获取图片对象与验证码文字
    image_object,code = check_code()
    #将验证码信息写入Session
    request.session['image_code'] = code #默认保存Cookie两周
    print(request.session.get('image_code'))
    #主动修改session过期时间
    request.session.set_expiry(60)#设置超时时间60秒  验证码一分钟后失效

    stream =BytesIO()
    image_object.save(stream,'png')#图片对象放入内存路径


    return HttpResponse(stream.getvalue())
#注销

def logout(request):
    request.session.flush()
    return redirect('index')